<template>
    <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="clearInput"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="initList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button
            type="primary"
            @click="add()"
            style="float: right"
            >新增</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="tabledata" style="width: 100%">
        <el-table-column label="账号" prop="logName"> </el-table-column>
        <el-table-column label="名称" prop="name"> </el-table-column>
        <el-table-column label="手机号" prop="mobilePhone"> </el-table-column>
        <el-table-column label="用户类型" prop="roleInfo.label"> </el-table-column>
        <el-table-column label="性别" prop="sex"> </el-table-column>
        <!-- 操作区域 -->
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              size="small"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              style="color: #fa6962"
              icon="el-icon-delete"
              size="small"
              @click="removeById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 新增 -->
    <el-dialog
      title="新增"
      :visible.sync="addVisible"
      width="50%"
      @close="addVisible = false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="logName">
          <el-input v-model="form.logName"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input v-model="form.mobilePhone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role">
            <el-option :label="item.label" :value="item.identity" v-for="(item, index) in roles" v-bind:key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageList, pageNameList, add, update, remove } from "#/User/admin.js";
import { allList} from "#/Authority/role.js";
import { addLogs } from '#/Home/Home.js'
var validatorPhone = function (rule, value, callback) {
  if (value === '') {
    callback(new Error('手机号不能为空'))
  } else if (!/^1\d{10}$/.test(value)) {
    callback(new Error('手机号格式错误'))
  } else {
    callback()
  }
}
var validatorPwd = function (rule, value, callback) {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (!/^[a-zA-Z0-9]{6,18}$/.test(value)) {
    callback(new Error('密码限制6-18位,只能由字母和数字组成'))
  } else {
    callback()
  }
}
export default {
    name: 'Admin',
    meta: {
        title: '管理员中心'
    },
    data() {
        return {
            queryInfo: {
                query: "",
                pageNum: 1,
                pageSize: 10,
            },
            // 统计公告的总数量
            total: 0,
            addVisible: false,
            addClosed: false,
            tabledata: [],
            roles: [],
            form: {
                id: "",
                logName: "",
                headImage: "",
                email: "",
                name: "",
                mobilePhone: "",
                password: "",
                role: 0
            },
            // 发布新公告表单规则
            formRules: {
                logName: [
                  { required: true, message: "请输入账号", trigger: "blur" }
                ],
                name: [
                  { required: true, message: "请输入昵称", trigger: "blur" }
                ],
                mobilePhone: [
                  { required: true, message: "请输入手机号", trigger: "blur" },
                   { required: true, validator: validatorPhone, trigger: 'blur' }
                ],
                password: [
                  { required: true, message: "请输入密码", trigger: "blur" },
                  { required: true, validator: validatorPwd, trigger: 'blur' },
                  {
                    min: 6,
                    max: 18,
                    message: "密码长度在6到18个字符",
                    trigger: "blur",
                  },
                ],
            },
        }
    },
    created() {
        this.initList();
        this.initRole();
    },
    methods: {
        initList() {
          if(this.queryInfo.query == ""){
            pageList(this.queryInfo.pageNum, this.queryInfo.pageSize).then(res => {
                // console.log(res);
                this.tabledata = res.data.users.admUsers.content;
                this.total = res.data.users.admUsers.totalElements;
            })
          }else{
            pageNameList(this.queryInfo.pageNum, this.queryInfo.pageSize, this.queryInfo.query).then(res => {
                // console.log(res);
                this.tabledata = res.data.users.admUsers.content;
                this.total = res.data.users.admUsers.totalElements;
            })
          }
            
        },
        initRole(){
          allList().then(res => {
            // console.log(res);
            this.roles = res.data.roles.roles;
          });
        },
        add(){
          this.isAdd = true;
          this.form =  {
            id: "",
            logName: "",
            headImage: "",
            email: "",
            name: "",
            mobilePhone: "",
            password: "",
            role: 0
          }
          this.addVisible = true;
        },
        edit(obj){
          this.isAdd = false;
          Object.assign(this.form, obj);
          // console.log(this.form);
          this.addVisible = true;
        },
        confirm(){
          this.$refs.formRef.validate((valid) => {
             if (!valid) return false;
            if(this.isAdd){
              add(this.form).then(res => {
                // console.log(res);
                if(res.data.ret == 0){
                  this.$message.success("添加成功");
                  this.addVisible = false;

                  addLogs({
                    userId: window.sessionStorage.getItem('userId'),
                    behavior: '新增了《' + this.form.logName + '》管理员',
                  })
                }
                this.initList();
              });
            }else{
              update(this.form.id, this.form).then(res => {
                // console.log(res);
                if(res.data.ret == 0){
                  this.$message.success("修改成功");
                  this.addVisible = false;

                  addLogs({
                    userId: window.sessionStorage.getItem('userId'),
                    behavior: '修改了《' + this.form.logName + '》管理员',
                  })
                }
                this.initList();
              });
            }
          })
          
        },
        removeById(id){
          this.$confirm(
            "此操作将永久删除该用户, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
              remove(id).then(res => {
                // console.log(res);
                if(res.data.ret == 0){
                  this.$message.success("删除成功");
                }
                this.initList();
            });
          });
        },
        // 清除输入框的内容
        clearInput() {
            this.queryInfo.pageNum = 1;
            this.queryInfo.pageSize = 10;
            this.searchFlag = false;
            this.initList();
        },
        // 每页的条目数改变
        handleSizeChange(newSize) {
            // console.log(newS)
            this.queryInfo.pageSize = newSize;
            this.initList();
        },
        // 页码改变
        handleCurrentChange(newPage) {
          //  console.log(newPage)
            this.queryInfo.pageNum = newPage;
            this.initList();
        },
    }
}
</script>

<style lang="less" scoped>

</style>
